import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

import '../app_logger.dart';

enum RecordStatus {
  idle,
  recording,
  error
}

// 带设备ID的录音状态
class DeviceRecordStatus {
  final RecordStatus status;
  final int deviceIndex; // 设备编号，1 或 2

  DeviceRecordStatus(this.status, this.deviceIndex);
}

class ConnectedDevice {
  final BluetoothDevice device;
  final BluetoothCharacteristic? notifyCharacteristic;
  final StreamSubscription? notifySubscription;
  final StreamSubscription? connectionStateSubscription;

  ConnectedDevice({
    required this.device,
    this.notifyCharacteristic,
    this.notifySubscription,
    this.connectionStateSubscription,
  });
}

class BleService {
  static final BleService _instance = BleService._internal();
  factory BleService() => _instance;
  BleService._internal();

  // 常量定义
  static const String _deviceNamePrefix = 'HQ STALK';
  static const String _serviceUUID = 'af40';
  static const String _notifyCharUUID = 'af42';

  // 设备与特征
  final List<ConnectedDevice> _connectedDevices = [];
  final StreamController<void> _connectionChangeController = StreamController<void>.broadcast();

  // 监听器
  final StreamController<RecordStatus> _recordStatusController = StreamController<RecordStatus>.broadcast();
  StreamSubscription? _stateSubscription;
  StreamSubscription? _scanSubscription;

  // 公开的流
  Stream<RecordStatus> get recordStatusStream => _recordStatusController.stream;
  Stream<BluetoothDevice> get scanResultsStream =>
      FlutterBluePlus.scanResults.expand((results) => results)
      //mac地址  是 CF:94:23:74:73:E5
      .where((result) => result.device.platformName.startsWith(_deviceNamePrefix)|| result.device.remoteId.str.startsWith("01:F4"))
      .map((result) => result.device);
  Stream<BluetoothAdapterState> get bluetoothStateStream => FlutterBluePlus.adapterState;
  Stream<void> get connectionChangeStream => _connectionChangeController.stream;

  // 扫描状态
  bool _isAutoConnectEnabled = true;
  bool _isScanning = false;

  // 状态
  bool get isConnected => _connectedDevices.isNotEmpty;
  bool get isScanning => _isScanning;
  bool get isAutoConnectEnabled => _isAutoConnectEnabled;

  set isAutoConnectEnabled(bool value) => _isAutoConnectEnabled = value;

  // 获取一个已连接的设备（如果有多个，返回第一个）
  BluetoothDevice? get connectedDevice =>
      _connectedDevices.isNotEmpty ? _connectedDevices.first.device : null;

  // 获取所有已连接设备
  List<ConnectedDevice> get allConnectedDevices {
    // 去除可能的重复项 (基于设备ID)
    final Map<String, ConnectedDevice> uniqueDevices = {};
    for (var device in _connectedDevices) {
      uniqueDevices[device.device.remoteId.str] = device;
    }
    return List.unmodifiable(uniqueDevices.values);
  }

  // 初始化
  Future<void> initialize() async {
    // 监听蓝牙状态变化
    _stateSubscription = FlutterBluePlus.adapterState.listen((state) {
      if (state == BluetoothAdapterState.off) {
        disconnectAll(); // 断开所有连接
      } else if (state == BluetoothAdapterState.on) {
        // 蓝牙开启时，重新尝试加载连接
        _loadExistingConnections();
        // 新增：如果没有连接设备，自动开始扫描
        _autoScanIfNeeded();
      }
    });

    // 加载已存在的连接
    await _loadExistingConnections();

    // 新增：如果没有连接设备，自动开始扫描
    await _autoScanIfNeeded();
  }

  /// 如果需要，自动开始扫描
  Future<void> _autoScanIfNeeded() async {
    // 等待一点时间让连接状态稳定
    await Future.delayed(const Duration(milliseconds: 300));

    try {
      // 如果蓝牙可用、自动连接开启且没有连接设备，开始扫描
      if (await FlutterBluePlus.isAvailable &&
          await FlutterBluePlus.isOn &&
          _isAutoConnectEnabled &&
          !isConnected &&
          !_isScanning) {
        log.d('没有连接设备，自动开始扫描...');
        await startScan();
      }
    } catch (e) {
      log.d('自动扫描失败: $e');
    }
  }

  // 加载已存在的连接
  Future<void> _loadExistingConnections() async {
    try {
      List<BluetoothDevice> devices = FlutterBluePlus.connectedDevices;
      List<BluetoothDevice> hqDevices = devices
          .where((device) => device.platformName.startsWith(_deviceNamePrefix))
          .toList();

      for (var device in hqDevices) {
        // 检查是否已在列表中
        if (_connectedDevices.any((d) => d.device.remoteId.str == device.remoteId.str)) {
          continue;
        }

        // 先添加基本连接信息
        final connectionStateSubscription = device.connectionState.listen((state) {
          if (state == BluetoothConnectionState.disconnected) {
            log.d('设备断开连接: ${device.platformName}');
            _removeDisconnectedDevice(device);
          }
        });

        _connectedDevices.add(ConnectedDevice(
          device: device,
          notifyCharacteristic: null,
          notifySubscription: null,
          connectionStateSubscription: connectionStateSubscription,
        ));

        // 通知连接变化
        _connectionChangeController.add(null);

        // 然后异步设置特征，并使用重试机制
        await _setUpDeviceConnectionWithRetry(device).catchError((e) {
          log.d('设置已存在设备特征最终失败: $e');
        });
      }
    } catch (e) {
      log.d('加载现有连接错误: $e');
    }
  }

  // 开始扫描并自动连接
  Future<void> startScan() async {
    if (_isScanning) return;
    _isScanning = true;

    if (await FlutterBluePlus.isAvailable && await FlutterBluePlus.isOn) {
      try {
        // 取消之前的订阅
        await _scanSubscription?.cancel();

        // 开始新的扫描
        await FlutterBluePlus.startScan(timeout: const Duration(seconds: 10));

        // 监听扫描结果，自动连接设备
        _scanSubscription = scanResultsStream.listen((device) async {
          if (_isAutoConnectEnabled) {
            // 检查是否已经连接
            final bool isAlreadyConnected = _connectedDevices.any(
              (d) => d.device.remoteId.str == device.remoteId.str
            );

            if (!isAlreadyConnected) {
              log.d('自动连接到设备: ${device.platformName}');
              await connectToDevice(device);
            }
          }
        });

        // 10秒后自动停止扫描
        Future.delayed(const Duration(seconds: 10), () {
          if (_isScanning) {
            stopScan();
          }
        });
      } catch (e) {
        log.d('开始扫描错误: $e');
        _isScanning = false;
      }
    } else {
      log.d('蓝牙不可用或未打开');
      _isScanning = false;
    }
  }

  // 停止扫描
  Future<void> stopScan() async {
    if (!_isScanning) return;

    try {
      await FlutterBluePlus.stopScan();
      await _scanSubscription?.cancel();
      _scanSubscription = null;
    } catch (e) {
      log.d('停止扫描错误: $e');
    } finally {
      _isScanning = false;
    }
  }

  // 连接设备
  Future<bool> connectToDevice(BluetoothDevice device) async {
    // 检查是否已连接
    final existingDeviceIndex = _connectedDevices.indexWhere(
        (d) => d.device.remoteId.str == device.remoteId.str);

    if (existingDeviceIndex != -1) {
      // 设备已连接
      return true;
    }

    try {
      // 连接设备
      log.d('正在连接设备: ${device.platformName}');
      await device.connect(autoConnect: false, timeout: const Duration(seconds: 15));

      // 设备已连接，创建连接状态监听
      final connectionStateSubscription = device.connectionState.listen((state) {
        if (state == BluetoothConnectionState.disconnected) {
          log.d('设备断开连接: ${device.platformName}');
          _removeDisconnectedDevice(device);
        }
      });

      // 创建一个初始连接实例
      final initialDevice = ConnectedDevice(
        device: device,
        notifyCharacteristic: null,  // 暂时为null，后面异步设置
        notifySubscription: null,    // 暂时为null，后面异步设置
        connectionStateSubscription: connectionStateSubscription,
      );

      // 添加到连接列表
      _connectedDevices.add(initialDevice);

      // 通知连接状态变化
      _connectionChangeController.add(null);

      log.d('设备基本连接成功: ${device.platformName}');

      // 异步设置特征和通知，使用重试机制，不阻塞连接流程
      _setUpDeviceConnectionWithRetry(device).then((success) {
        if (!success) {
          log.d('警告: 设备 ${device.platformName} 已连接，但特征设置最终失败');
        } else {
          log.d('设备特征设置成功: ${device.platformName}');
        }
      }).catchError((e) {
        log.d('设置设备特征时最终失败: $e');
      });

      return true;
    } catch (e) {
      log.d('连接设备时出错: $e');
      return false;
    }
  }

  // 带重试机制的设备特征设置
  Future<bool> _setUpDeviceConnectionWithRetry(BluetoothDevice device, {int maxRetries = 3}) async {
    int retryCount = 0;
    bool success = false;

    while (retryCount < maxRetries && !success) {
      try {
        // 第一次尝试不延迟，后续尝试逐渐增加延迟
        if (retryCount > 0) {
          final delay = Duration(milliseconds: 500 * retryCount);
          log.d('重试设置特征 #${retryCount + 1}，延迟: ${delay.inMilliseconds}ms, 设备: ${device.platformName}');
          await Future.delayed(delay);
        }

        success = await _setUpDeviceConnection(device);

        if (success) {
          if (retryCount > 0) {
            log.d('设置特征成功 (重试 #${retryCount + 1}): ${device.platformName}');
          }
          return true;
        } else {
          log.d('设置特征失败 (尝试 #${retryCount + 1}): ${device.platformName}');
        }
      } catch (e) {
        log.d('设置特征出错 (尝试 #${retryCount + 1}): $e');
      }

      retryCount++;
    }

    return success;
  }

  // 设置设备连接的特征服务
  Future<bool> _setUpDeviceConnection(BluetoothDevice device) async {
    try {
      // 查找设备在列表中的索引
      final deviceIndex = _connectedDevices.indexWhere(
          (d) => d.device.remoteId.str == device.remoteId.str);

      if (deviceIndex == -1) {
        log.d('设置特征时发现设备不在连接列表中: ${device.platformName}');
        return false;
      }

      // 获取当前连接实例
      final connectedDevice = _connectedDevices[deviceIndex];

      // 如果已经设置了特征，则直接返回成功
      if (connectedDevice.notifyCharacteristic != null) {
        return true;
      }

      // 发现服务
      List<BluetoothService> services = await device.discoverServices();
      BluetoothCharacteristic? notifyChar;

      for (BluetoothService service in services) {
        if (service.uuid.toString().toLowerCase().contains(_serviceUUID)) {
          for (BluetoothCharacteristic characteristic in service.characteristics) {
            if (characteristic.uuid.toString().toLowerCase().contains(_notifyCharUUID)) {
              notifyChar = characteristic;
              break;
            }
          }
        }
      }

      if (notifyChar != null) {
        // 设置通知
        await notifyChar.setNotifyValue(true);

        // 监听通知 - 添加设备索引
        final actualDeviceIndex = deviceIndex + 1;  // 设备索引从1开始
        final subscription = notifyChar.onValueReceived.listen(
          (data) => _handleNotification(data, actualDeviceIndex)
        );

        // 更新连接列表中的设备信息
        _connectedDevices[deviceIndex] = ConnectedDevice(
          device: device,
          notifyCharacteristic: notifyChar,
          notifySubscription: subscription,
          connectionStateSubscription: connectedDevice.connectionStateSubscription,
        );

        // 通知连接状态变化
        _connectionChangeController.add(null);

        log.d('设置设备特征和通知成功: ${device.platformName}, 索引: $actualDeviceIndex');
        return true;
      } else {
        log.d('未找到通知特征');
        return false;
      }
    } catch (e) {
      log.d('设置设备特征出错: $e');
      return false;
    }
  }

  // 移除断开连接的设备
  void _removeDisconnectedDevice(BluetoothDevice device) {
    final index = _connectedDevices.indexWhere(
        (d) => d.device.remoteId.str == device.remoteId.str);

    if (index != -1) {
      final connectedDevice = _connectedDevices[index];

      // 取消订阅
      connectedDevice.notifySubscription?.cancel();
      connectedDevice.connectionStateSubscription?.cancel();

      // 从列表中移除
      _connectedDevices.removeAt(index);

      // 通知连接状态变化
      _connectionChangeController.add(null);

      log.d('已从列表中移除断开连接的设备: ${device.platformName}');
    }
  }

  // 断开指定设备
  Future<void> disconnectDevice(BluetoothDevice device) async {
    // 查找指定的设备
    final index = _connectedDevices.indexWhere(
        (d) => d.device.remoteId.str == device.remoteId.str);

    if (index != -1) {
      final connectedDevice = _connectedDevices[index];

      // 取消通知订阅
      if (connectedDevice.notifySubscription != null) {
        await connectedDevice.notifySubscription!.cancel();
      }

      // 取消连接状态订阅
      if (connectedDevice.connectionStateSubscription != null) {
        await connectedDevice.connectionStateSubscription!.cancel();
      }

      // 取消通知
      if (connectedDevice.notifyCharacteristic != null) {
        try {
          await connectedDevice.notifyCharacteristic!.setNotifyValue(false);
        } catch (e) {
          log.d('取消通知时出错: $e');
        }
      }

      // 断开设备连接
      try {
        await device.disconnect();
      } catch (e) {
        log.d('断开设备连接时出错: $e');
      }

      // 从列表中移除
      _connectedDevices.removeAt(index);

      // 通知连接状态变化
      _connectionChangeController.add(null);

      log.d('手动断开设备连接: ${device.platformName}');
    }
  }

  // 断开所有连接
  Future<void> disconnectAll() async {
    for (var connectedDevice in List.from(_connectedDevices)) {
      await disconnectDevice(connectedDevice.device);
    }

    _connectedDevices.clear();
    _recordStatusController.add(RecordStatus.idle);

    // 通知连接状态变化
    _connectionChangeController.add(null);
  }

  // 断开连接（保持兼容旧代码）
  Future<void> disconnect() async {
    if (_connectedDevices.isNotEmpty) {
      await disconnectDevice(_connectedDevices.first.device);
    }
  }

  // BleService类中添加
  DateTime? _lastStatusChangeTime;
  RecordStatus? _lastStatus;

  // 修改_handleNotification方法
  void _handleNotification(List<int> data, int deviceIndex) {
    if (data.length < 4) return;

    try {
      // 检查第4位的值判断是开始还是结束录音
      int statusByte = data[3];
      RecordStatus status;

      if (statusByte == 0x01) {
        // 开始录音信号
        status = RecordStatus.recording;
        log.d('收到设备$deviceIndex开始录音命令');
      } else if (statusByte == 0x00) {
        // 停止录音信号
        status = RecordStatus.idle;
        log.d('收到设备$deviceIndex停止录音命令');
      } else {
        return; // 忽略未知状态
      }

      // 防抖处理 - 如果短时间内收到相同状态的命令，忽略它
      final now = DateTime.now();
      if (_lastStatusChangeTime != null &&
          _lastStatus == status &&
          now.difference(_lastStatusChangeTime!).inMilliseconds < 200) { // 设置200毫秒的防抖时间
        log.d('忽略重复的${status == RecordStatus.recording ? "开始" : "停止"}录音命令 (防抖)');
        return;
      }

      // 更新最后状态变更时间和状态
      _lastStatusChangeTime = now;
      _lastStatus = status;

      // 发送到状态流
      _recordStatusController.add(status);

    } catch (e) {
      log.d('处理通知错误: $e');
      _recordStatusController.add(RecordStatus.error);
    }
  }

  // 获取已连接设备列表
  Future<List<BluetoothDevice>> getConnectedDevices() async {
    List<BluetoothDevice> devices = FlutterBluePlus.connectedDevices;
    return devices.where((device) => device.platformName.startsWith(_deviceNamePrefix)).toList();
  }

  // 检查设备连接状态
  Future<void> checkDevicesConnectionStatus() async {
    if (_connectedDevices.isEmpty) return;

    List<BluetoothDevice> actuallyConnectedDevices = FlutterBluePlus.connectedDevices;
    Set<String> connectedIds = actuallyConnectedDevices
        .map((device) => device.remoteId.str)
        .toSet();

    // 检查我们列表中的设备是否实际连接
    for (var device in List.from(_connectedDevices)) {
      if (!connectedIds.contains(device.device.remoteId.str)) {
        log.d('检测到设备未实际连接: ${device.device.platformName}');
        await disconnectDevice(device.device);
      }
    }
  }

  // 销毁
  Future<void> dispose() async {
    await stopScan();
    await disconnectAll();

    if (_stateSubscription != null) {
      await _stateSubscription!.cancel();
      _stateSubscription = null;
    }

    if (_scanSubscription != null) {
      await _scanSubscription!.cancel();
      _scanSubscription = null;
    }

    await _recordStatusController.close();
    await _connectionChangeController.close();
  }
}
